package com.yunkeji.system.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunkeji.common.core.domain.PageQuery;
import com.yunkeji.common.core.page.TableDataInfo;
import com.yunkeji.common.exception.ServiceException;
import com.yunkeji.common.msg.PushMessage;
import com.yunkeji.common.utils.StringUtils;
import com.yunkeji.dao.domain.SysIpDeviceBanned;
import com.yunkeji.dao.mapper.AppUserMapper;
import com.yunkeji.dao.mapper.sys.SysIpDeviceBannedMapper;
import com.yunkeji.dao.mapper.sys.SysLogininforMapper;
import com.yunkeji.dao.vo.sys.SysIpDeviceBannedVo;
import com.yunkeji.system.domain.bo.SysIpDeviceBannedBo;
import com.yunkeji.system.service.SysIpDeviceBannedService;

import lombok.RequiredArgsConstructor;

import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 封禁IP和设备记录Service业务层处理
 *
 * @author yunkeji
 * @date 2024-09-26
 */
@RequiredArgsConstructor
@Service
public class SysIpDeviceBannedServiceImpl implements SysIpDeviceBannedService {

    private final SysIpDeviceBannedMapper baseMapper;

    private final AppUserMapper appUserMapper;

    private final SysLogininforMapper sysLogininforMapper;

    /** 查询封禁IP和设备记录 */
    @Override
    public SysIpDeviceBannedVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /** 查询封禁IP和设备记录列表 */
    @Override
    public TableDataInfo<SysIpDeviceBannedVo> queryPageList(
            SysIpDeviceBannedBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysIpDeviceBanned> lqw = buildQueryWrapper(bo);
        Page<SysIpDeviceBannedVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /** 查询封禁IP和设备记录列表 */
    @Override
    public List<SysIpDeviceBannedVo> queryList(SysIpDeviceBannedBo bo) {
        LambdaQueryWrapper<SysIpDeviceBanned> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysIpDeviceBanned> buildQueryWrapper(SysIpDeviceBannedBo bo) {
        LambdaQueryWrapper<SysIpDeviceBanned> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, SysIpDeviceBanned::getUserId, bo.getUserId());
        lqw.eq(
                StringUtils.isNotBlank(bo.getReason()),
                SysIpDeviceBanned::getReason,
                bo.getReason());
        lqw.eq(bo.getEndTime() != null, SysIpDeviceBanned::getEndTime, bo.getEndTime());
        lqw.eq(bo.getLimitType() != null, SysIpDeviceBanned::getLimitType, bo.getLimitType());
        lqw.eq(bo.getPlatformId() != null, SysIpDeviceBanned::getPlatformId, bo.getPlatformId());
        lqw.eq(bo.getBannedType() != null, SysIpDeviceBanned::getBannedType, bo.getBannedType());
        lqw.eq(
                StringUtils.isNotBlank(bo.getTarget()),
                SysIpDeviceBanned::getTarget,
                bo.getTarget());
        lqw.orderByDesc(SysIpDeviceBanned::getCreateTime);
        return lqw;
    }

    /** 新增封禁IP和设备记录 */
    @Override
    @CachePut(value = "banned", key = "#bo.target")
    public String insertByBo(SysIpDeviceBannedBo bo) {
        SysIpDeviceBanned add = BeanUtil.toBean(bo, SysIpDeviceBanned.class);
        int count = baseMapper.countByTarget(add.getTarget());
        if (count > 0) {
            throw new ServiceException("该IP或设备已被封禁。");
        }
        baseMapper.insert(add);
        // 获取当前设备或IP上的用户
        List<Long> platformIds = sysLogininforMapper.selectPlatformIdByIPOrDevice(bo.getTarget());
        platformIds.forEach(platformId -> PushMessage.kickout(platformId, "设备或IP已被封禁"));
        return bo.getTarget();
    }

    /** 修改封禁IP和设备记录 */
    @Override
    public Boolean updateByBo(SysIpDeviceBannedBo bo) {
        SysIpDeviceBanned update = BeanUtil.toBean(bo, SysIpDeviceBanned.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /** 保存前的数据校验 */
    private void validEntityBeforeSave(SysIpDeviceBanned entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /** 批量删除封禁IP和设备记录 */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
